<template>
  <div class="chart-item medium">
    <div class="chart-header">
      <h3>在途物料分析</h3>
      <div class="chart-tabs">
        <el-radio-group v-model="analysisMode" size="small" @change="handleAnalysisModeChange">
          <el-radio-button label="status">状态分布</el-radio-button>
          <el-radio-button label="route">路线分析</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="chart-content">
      <div v-if="analysisMode === 'status'" class="transit-summary">
        <div class="summary-item">
          <div class="summary-value">{{ totalTransit }}</div>
          <div class="summary-label">总在途数量</div>
        </div>
        <div class="summary-item">
          <div class="summary-value">{{ avgTransitDays }}</div>
          <div class="summary-label">平均在途天数</div>
        </div>
      </div>
      <div ref="transitChart" class="chart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'MaterialTransitChart',
  props: {
    transitData: {
      type: Object,
      default: () => ({
        normal: 1245,
        delayed: 89,
        abnormal: 23,
        arriving: 156
      })
    }
  },
  data() {
    return {
      analysisMode: 'status',
      chart: null,
      routeData: [
        { source: '华东库房', target: '华南库房', value: 450 },
        { source: '华东库房', target: '华北库房', value:320 },
        { source: '华东库房', target: '西南库房', value:180 },
        { source: '华南库房', target: '华北库房', value: 280 },
        { source: '华南库房', target: '西南库房', value: 220 },
        { source: '华南库房', target: '其他库房', value: 150 },
        { source: '华北库房', target: '西南库房', value: 380 },
        { source: '华北库房', target: '其他库房', value: 120 },
        { source: '西南库房', target: '其他库房', value: 200 }
      ]
    }
  },
  computed: {
    totalTransit() {
      return this.transitData.normal + this.transitData.delayed +
             this.transitData.abnormal + this.transitData.arriving
    },
    avgTransitDays() {
      return '3.2天'
    },
    statusData() {
      return [
        {
          name: '正常在途',
          value: this.transitData.normal,
          itemStyle: { color: '#5470c6' }
        },
        {
          name: '延迟在途',
          value: this.transitData.delayed,
          itemStyle: { color: '#fac858' }
        },
        {
          name: '异常在途',
          value: this.transitData.abnormal,
          itemStyle: { color: '#ee6666' }
        },
        {
          name: '即将到达',
          value: this.transitData.arriving,
          itemStyle: { color: '#91cc75' }
        }
      ]
    }
  },
  mounted() {
    setTimeout(() => {
      this.initChart()
    }, 100)
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  watch: {
    transitData: {
      handler() {
        this.updateChart()
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.transitChart
        if (!chartDom) {
          console.warn('TransitChart DOM element not found')
          return
        }

        this.chart = echarts.init(chartDom)
        this.updateChart()

        window.addEventListener('resize', () => {
          if (this.chart) {
            this.chart.resize()
          }
        })
      })
    },

    updateChart() {
      if (!this.chart) return

      let option = {}

      if (this.analysisMode === 'status') {
        // 状态分布饼图
        option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            bottom: '5%',
            left: 'center',
            itemGap: 15,
            textStyle: {
              fontSize: 11
            }
          },
          series: [
            {
              name: '在途状态',
              type: 'pie',
              radius: ['35%', '65%'],
              center: ['50%', '45%'],
              data: this.statusData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                formatter: '{b}\n{c}',
                fontSize: 10
              },
              labelLine: {
                show: true
              }
            }
          ]
        }
      } else {
        // 路线分析桑基图
        const nodes = []
        const links = []

        // 提取所有库房节点
        const warehouses = new Set()
        this.routeData.forEach(item => {
          warehouses.add(item.source)
          warehouses.add(item.target)
        })

        // 创建节点
        Array.from(warehouses).forEach(warehouse => {
          nodes.push({ name: warehouse })
        })

        // 创建连接
        this.routeData.forEach(item => {
          links.push({
            source: item.source,
            target: item.target,
            value: item.value
          })
        })

        option = {
          tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove',
            formatter: function(params) {
              if (params.dataType === 'edge') {
                return `${params.data.source} → ${params.data.target}<br/>运输量: ${params.data.value}`
              } else {
                return `${params.name}<br/>库房节点`
              }
            }
          },
          series: [
            {
              type: 'sankey',
              layout: 'none',
              emphasis: {
                focus: 'adjacency'
              },
              data: nodes,
              links: links,
              orient: 'horizontal',
              left: '5%',
              right: '5%',
              top: '5%',
              bottom: '5%',
              nodeWidth: 15,
              nodeGap: 8,
              nodeAlign: 'justify',
              itemStyle: {
                borderWidth: 1,
                borderColor: '#aaa'
              },
              lineStyle: {
                color: 'source',
                curveness: 0.5
              },
              label: {
                fontSize: 10,
                color: '#333'
              }
            }
          ]
        }
      }

      this.chart.setOption(option, true)
    },

    handleAnalysisModeChange(mode) {
      this.analysisMode = mode
      this.updateChart()
      this.$emit('analysis-mode-change', mode)
    }
  }
}
</script>

<style lang="scss" scoped>
.transit-summary {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;

  .summary-item {
    flex: 1;
    text-align: center;
    padding: 8px;
    background: #f8f9fa;
    border-radius: 4px;

    .summary-value {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 2px;
    }

    .summary-label {
      font-size: 10px;
      color: #909399;
    }
  }
}

.chart-content {
  .chart {
    width: 100%;
    height: 260px;
  }
}

.chart-tabs {
  ::v-deep .el-radio-button__inner {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>
